package cn.yto.print.utils;

import cn.yto.print.controller.ToastController;
import de.felixroske.jfxsupport.GUIState;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FxToastUtil {

    private static final Logger logger = LogManager.getLogger(CommonUtil.class);

    public static Stage toastStage = null;

    public static void showToast(String content) {
        try {
            FXMLLoader loader = new FXMLLoader(FxToastUtil.class.getResource("/fxml/toast.fxml"));
            StackPane stackPane = loader.load();
            Scene scene = new Scene(stackPane);
            Stage toastStage = getToastStage(scene);
            // 设置 Stage 给 controller，以便控制关闭
            ToastController controller = loader.getController();
            controller.setToastStage(toastStage);
            controller.showMessage(content);
            toastStage.show();
        } catch (Exception e) {
            logger.error("吐司消息弹框异常", e);
        }
    }

    private static Stage getToastStage(Scene scene) {
        if (null == toastStage) {
            toastStage = new Stage();
            toastStage.initStyle(StageStyle.UNDECORATED);
            toastStage.setOpacity(0.8);
            toastStage.setAlwaysOnTop(true);
            toastStage.initOwner(GUIState.getStage());
            toastStage.initModality(Modality.APPLICATION_MODAL);
        }
        toastStage.setScene(scene);
        return toastStage;
    }

}
